package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.gdpu.model.Person;
import org.gdpu.service.PersonService;
import org.gdpu.vo.PersonVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-4
 * Time: 下午6:51
 * To change this template use File | Settings | File Templates.
 */
@Component("login")
@Scope("prototype")
public class LoginAction extends MyActionSupport implements ModelDriven<PersonVO> {

    private PersonService personService;

    private final PersonVO personVO = new PersonVO();

    private static final Logger logger = LogManager.getLogger(LoginAction.class);

    //用户登录
    @Override
    public String execute() throws Exception {

        if (personVO.getAccout() == null) return ERROR;
        Person person = personService.findPersonByAccout(personVO.getAccout());
        if (person == null) return ERROR;
        logger.entry(person.getAccout());
        /*to do: when person doesn't have the purview group,
                 we should redirect a special page for him, like visitor.*/
        if (personVO.getPassword().equals(person.getPassword())) {
            if (person.getGroups() == null) {
                personVO.setResultMessage("您还没有分配相应的角色,不存在任何权限!请找相关人士联系!");
                return ERROR;
            }

            if (!personVO.getGroup().equals(person.getGroups().getGroupName())) {
                personVO.setResultMessage("该用户不属于该角色！");
                return ERROR;
            }

            storePersonToSession(person);
            logger.info("user:" + person.getPersonName() + ", group:"
                    + person.getGroups().getGroupName() + " login the system.");
            //TODO:Can change
            HttpServletRequest request = ServletActionContext.getRequest();
            Object obj =  request.getSession().getAttribute("requestURI");
            if(obj != null) {
                view = obj.toString();
            }else {
                view = "/index.jsp";
                return VIEW;
            }
            return "view";

                //return SUCCESS;
        }
        logger.warn("用户:"+person.getAccout() +"   密码错误！");
        logger.exit(person.getAccout());
        personVO.setResultMessage("密码错误！");
        return ERROR;

    }

    public String loginOut() throws Exception {
        HttpSession session = ServletActionContext.getRequest().getSession();
        Person person = (Person) session.getAttribute("person");
        if (person != null) {
            logger.info(person.getAccout() + " leave the system by security way");
            session.removeAttribute("person");
            session.invalidate();
        }
        view = "/index.jsp";
        return VIEW;
    }


    //忘记密码
    public String forget() {
        Person person = personService.findPersonByAccout(personVO.getAccout());
        if (person == null) {
            personVO.setResultMessage("该用户不存在！");
            return ERROR;
        }
        if (personVO.getPersonName().equals(person.getPersonName())) {
            personVO.setResultMessage("用户密码：" + person.getPassword());
            return SUCCESS;
        }
        personVO.setResultMessage("用户信息有误！");
        return ERROR;
    }

    @Override
    public PersonVO getModel() {
        return personVO;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }


    private void storePersonToSession(Person target) {
        HttpSession session = ServletActionContext.getRequest().getSession();
        Person storedPerson = (Person) session.getAttribute("person");
        if (storedPerson == null || !storedPerson.equals(target)) {
            session.setAttribute("person", target);
            session.setAttribute("loginKey", "success");
            session.setMaxInactiveInterval(-1);
        }
    }
}

